﻿using System;
using System.Collections.Generic;
using System.Linq;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Saisie_des_prélèvements.Models;
using Saisie_des_prélèvements.ViewModels;
using Windows.UI.Xaml.Media;
using Windows.UI.Popups;
using System.Globalization;
using Saisie_des_prélèvements.Common;

// The Basic Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234237

namespace Saisie_des_prélèvements.Views
{
    /// <summary>
    /// A basic page that provides characteristics common to most applications.
    /// </summary>
    public sealed partial class ClientTakenPage : Saisie_des_prélèvements.Common.LayoutAwarePage
    {
        int CurrentClientTaken = 0;
        int CurrentTakenID = 0;
        Grid g = null;

        public ClientTakenPage()
        {
            this.InitializeComponent();
        }

        /// <summary>
        /// Populates the page with content passed during navigation.  Any saved state is also
        /// provided when recreating a page from a prior session.
        /// </summary>
        /// <param name="navigationParameter">The parameter value passed to
        /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
        /// </param>
        /// <param name="pageState">A dictionary of state preserved by this page during an earlier
        /// session.  This will be null the first time a page is visited.</param>
        protected override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
        {
            CurrentClientTaken = int.Parse(navigationParameter == null ? App.ClientTakenId.ToString() : navigationParameter.ToString());
            App.ClientTakenId = CurrentClientTaken;
            using (var db = new SQLite.SQLiteConnection(App.DBPath))
            {
                k_client_taken info = db.Table<k_client_taken>().Where(c => c.client_taken_id == CurrentClientTaken).First();
                k_setting set = db.Table<k_setting>().First();

                if (info.client_seq == null || info.client_seq == "")
                {
                    // Set Number document.
                    info.client_seq = string.Format("{0}{1}{2}{3}{4}{5}", info.client_taken_code, DateTime.Now.ToString("yy"), DateTime.Now.ToString("MM"), DateTime.Now.ToString("dd"), App.Marchine, set.client_seq);
                    db.Update(info);
                    set.client_seq = (int.Parse(set.client_seq) + 1).ToString("00000");
                    db.Update(set);
                }

                txtClientCode.Text = info.client_taken_code;
                txtNoDos.Text = info.client_seq; //

                List<TakenViewModel> takens = (new TakenViewModel()).GetTakenListByClient(CurrentClientTaken);

                // Check all taken meet condition
                foreach (TakenViewModel i in takens)
                {
                    // Set taken status to 99 when meet condition
                    if (!TakenCondition(i)) i.Status = 99;
                }

                // Remove all condition that meet condition from list.
                takens.RemoveAll(t=>t.Status==99);
                itemListView.ItemsSource = takens;
                itemListView.SelectedValuePath = "TakenId";

                


            }
            
        }

        /// <summary>
        /// Preserves state associated with this page in case the application is suspended or the
        /// page is discarded from the navigation cache.  Values must conform to the serialization
        /// requirements of <see cref="SuspensionManager.SessionState"/>.
        /// </summary>
        /// <param name="pageState">An empty dictionary to be populated with serializable state.</param>
        protected override void SaveState(Dictionary<String, Object> pageState)
        {
        }

        private void btnNew_Click(object sender, RoutedEventArgs e)
        {
            this.Frame.Navigate(typeof(TakenNewPage), CurrentClientTaken);
        }

        private async void btnDelete_Click(object sender, RoutedEventArgs e)
        {
            List<TakenViewModel> taken = (List<TakenViewModel>)itemListView.ItemsSource;
            CurrentTakenID = int.Parse(((Button)sender).Tag.ToString());
            int s = taken.Where(t => t.TakenId == CurrentTakenID).First().Status;
            g = ((Grid)((Button)sender).Parent);

            // open the Popup if it isn't open already
            if (s == 0 || s == 2 || s == 3)
            {
                if (!LightDismissAnimatedPopup.IsOpen)
                {
                    LightDismissAnimatedPopup.IsOpen = true;
                }
            }
            else
            {
                // Create the message dialog and set its content; it will get a default "Close" button since there aren't any other buttons being added
                var messageDialog = new MessageDialog(new msg().client_enable);

                // Add commands and set their callbacks; both buttons use the same callback function instead of inline event handlers
                messageDialog.Commands.Add(new UICommand("OK", new UICommandInvokedHandler(this.CommandInvokedHandler)));
                messageDialog.Commands.Add(new UICommand(new msg().msgCancel, new UICommandInvokedHandler(this.CommandInvokedHandler)));

                // Set the command that will be invoked by default
                messageDialog.DefaultCommandIndex = 0;

                // Set the command to be invoked when escape is pressed
                messageDialog.CancelCommandIndex = 1;

                // Show the message dialog and wait
                await messageDialog.ShowAsync();
            }
            
           
        }

        /// <summary>
        /// Callback function for the invocation of the dialog commands.
        /// </summary>
        /// <param name="command">The command that was invoked.</param>
        private void CommandInvokedHandler(IUICommand command)
        {
            if (command.Label == "OK")
            {
                using (var db = new SQLite.SQLiteConnection(App.DBPath))
                {
                    var taken = db.Table<k_taken>().Where(k => k.taken_id == CurrentTakenID).First();
                    taken.status = 2;
                    taken.user_create = App.CurrentUserId;
                    taken.date_create = DateTime.Now;
                    db.Update(taken);
                }
                g.Background = new SolidColorBrush(Windows.UI.Color.FromArgb(255, 255, 255, 255));

                List<TakenViewModel> vtaken = (List<TakenViewModel>)itemListView.ItemsSource;
                vtaken.Where(t => t.TakenId == CurrentTakenID).First().Status = 2;
            }

        }

        private void CloseAnimatedPopupClicked(object sender, RoutedEventArgs e)
        {
            // if the Popup is open, then close it
            if (LightDismissAnimatedPopup.IsOpen) { LightDismissAnimatedPopup.IsOpen = false; }
        }

        private void LightDismissAnimatedPopup_Loaded(object sender, RoutedEventArgs e)
        {
            LightDismissAnimatedPopup.HorizontalOffset = (Window.Current.Bounds.Width - ppuBorder.Width) / 2;
            LightDismissAnimatedPopup.VerticalOffset = (Window.Current.Bounds.Height - ppuBorder.Height) / 2;
            txtComment.Focus(Windows.UI.Xaml.FocusState.Keyboard);
        }

        private void btnOK_Click(object sender, RoutedEventArgs e)
        {
            using (var db = new SQLite.SQLiteConnection(App.DBPath))
            {
                var taken = db.Table<k_taken>().Where(k => k.taken_id == CurrentTakenID).First();
                taken.reason_delete = txtComment.Text;
                taken.status = 1;
                taken.user_create = App.CurrentUserId;
                taken.date_create = DateTime.Now;

                db.Update(taken);
            }
            g.Background = new SolidColorBrush(Windows.UI.Color.FromArgb(255,255,123,33));

            List<TakenViewModel> vtaken = (List<TakenViewModel>)itemListView.ItemsSource;
            vtaken.Where(t => t.TakenId == CurrentTakenID).First().Status = 1;
            // if the Popup is open, then close it
            if (LightDismissAnimatedPopup.IsOpen) { LightDismissAnimatedPopup.IsOpen = false; }
        }

        private void itemListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (itemListView.SelectedIndex == -1) return;
            TakenViewModel taken = (TakenViewModel)itemListView.SelectedItem;
            if (taken.Status == 1)
            {
                itemListView.SelectedIndex = -1;
                return;
            }
            //string scode = taken.SurvCode == null ? "" : taken.SurvCode;
            //if (scode != "")
            //{
            //    DateTimeFormatInfo dfi = DateTimeFormatInfo.CurrentInfo;
            //    Calendar cal = dfi.Calendar;
            //    string weekOfYear = cal.GetWeekOfYear(DateTime.Today, dfi.CalendarWeekRule, dfi.FirstDayOfWeek).ToString();
            //    string dOw = ((int)DateTime.Now.DayOfWeek == 0 ? 7 : (int)DateTime.Now.DayOfWeek).ToString();
            //    if ((!taken.TakenDay.Split('-').Contains<string>(dOw)) || !taken.TakenMonth.Split('-').Contains<string>(DateTime.Now.Month.ToString()) || !taken.TakenYear.Split('-').Contains<string>(weekOfYear))
            //    {
            //        // Create the message dialog and set its content; it will get a default "Close" button since there aren't any other buttons being added
            //        var messageDialog = new MessageDialog(new msg().client_block);

            //        // Show the message dialog and wait
            //        await messageDialog.ShowAsync();
            //        itemListView.SelectedIndex = -1;
            //        return;
            //    }
            //}

            this.Frame.Navigate(typeof(TakenSummaryPage), itemListView.SelectedValue.ToString());
        }

        private bool TakenCondition(TakenViewModel taken)
        {
            string scode = taken.SurvCode == null ? "" : taken.SurvCode;
            bool _pass = false;
            if (scode != "")
            {
                DateTimeFormatInfo dfi = DateTimeFormatInfo.CurrentInfo;
                Calendar cal = dfi.Calendar;
                string weekOfYear = cal.GetWeekOfYear(DateTime.Today, dfi.CalendarWeekRule, dfi.FirstDayOfWeek).ToString();
                string dOw = ((int)DateTime.Now.DayOfWeek == 0 ? 7 : (int)DateTime.Now.DayOfWeek).ToString();
                if (weekOfYear == "53") weekOfYear = "52";

                if (taken.TakenYear.Split('-').Contains<string>(weekOfYear))
                    if (taken.TakenMonth.Split('-').Contains<string>(DateTime.Now.Month.ToString()))
                        _pass = taken.TakenDay.Split('-').Contains<string>(dOw);
            }
            return _pass;
        }

        private void GoBack(object sender, RoutedEventArgs e)
        {
            this.Frame.Navigate(typeof(ClientsPage));
        }

    }
}
